package db4oToOracle.obj1test;


import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.googlecode.datawander.connectors.Db4oUtil;
import com.googlecode.datawander.connectors.OracleConnector;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author MarcinStachniuk
 */
public class Login {

    private String login;
    private String password;

    public static void saveAllRecords(Login[] logins) throws Exception {
        if(logins != null) {
            Connection conn = OracleConnector.getConnection();
            for(Login o : logins) {
                o.saveRecord(conn);
            }
        }
    }

    private void saveRecord(Connection conn) throws SQLException {
        String sql = "insert into \"Login\" (\"GENERATED_ID\", \"login\", \"password\", \"GEN_login_AppUser\") " +
                "values (?,?,?,?)";
        PreparedStatement stmt = conn.prepareStatement(sql);
        stmt.setLong(1, getIdFromDb4o());
        stmt.setString(2, login);
        stmt.setString(3, password);

        long id=0;
        ObjectSet<AppUser> mySet = AppUser.getAppUserByLoginFromDb4o(this);  // 1:1
        if(mySet.size() != 0) {
            if(mySet.size() == 1) {     // OK
                AppUser temp = mySet.get(0);
                id = temp.getIdFromDb4o();
                stmt.setLong(4, temp.getIdFromDb4o());
            } else {
                System.out.println("Błąd - powinno znales jedna referencje");
            }
        } else {        // nie ma, moze nie byc
            //
        }

        try {
            stmt.executeUpdate();
            System.out.println("Zachowano Login: id "+getIdFromDb4o() + " login: " + login +
                " pass: " + password + " FK "+id);
        } catch(SQLException e) {
            System.out.println("FAILED SAVE Login: id "+getIdFromDb4o() + " login: " + login +
                " pass: " + password + " FK "+id);
            throw e;
        }
        
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * Pobiera id z db4o. Zakładam ze wynik bedzie inny niz zero, w przeciwnym
     * wypadku bedzie to obiekt ktorego nie bylo w db4o
     * @return
     */
    public long getIdFromDb4o() {
        ObjectContainer db = Db4oUtil.getObjectContainer();
        long id = db.ext().getID(this);
        return id;
    }
}
